package com.car.loan.project.xr.util.repayment.impl;

import com.alibaba.fastjson.JSON;
import com.car.loan.project.cm.util.enunms.CarBrandType;
import com.car.loan.project.xr.util.repayment.RepaymentFormulaInterface;
import com.car.loan.project.xr.util.repayment.RepaymentInfo;
import com.car.loan.project.xr.util.repayment.RepaymentInfoParam;
import com.car.loan.project.xr.util.repayment.RepaymentPlan;
import com.car.loan.project.xr.util.repayment.RepaymentPlanParam;
import com.car.loan.project.xr.util.repayment.RepaymentPlanUtil;
import java.math.BigDecimal;
import java.math.MathContext;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * @author huangding
 * @description 农业银行还款公式
 * @date 2019/12/31 9:35
 */
@Service("abcRepaymentFormula")
public class AbcRepaymentFormula implements RepaymentFormulaInterface {

    /**
     * A=融资金额 B=分期金额 C=分期期数 D=银行基础费率 首月本金=每月本金=四舍五入到整（A/C） 末月本金=A-每月本金*（C-1）
     * 首月利息=每月利息=四舍五入到2位小数（A*D/C） 末月利息=A*D-每月利息*（C-1）
     *
     * @param repaymentInfoParam 还款信息参数
     */
    @Override
    public RepaymentInfo getRepaymentInfo(RepaymentInfoParam repaymentInfoParam) {
        //融资金额
        BigDecimal a = repaymentInfoParam.getFinancingAmount();
        //C=分期期数
        BigDecimal c = new BigDecimal(repaymentInfoParam.getTerm());
        //D=银行基础费率
        BigDecimal d = repaymentInfoParam.getRate();

        //每月，首月本金(首月本金=每月本金=四舍五入到整（A/C）)
        BigDecimal monthRepayPrincipal, firstRepayPrincipal;
        firstRepayPrincipal = monthRepayPrincipal = a.divide(c, MathContext.DECIMAL128)
            .setScale(0, BigDecimal.ROUND_HALF_UP);

        //末月本金=A-每月本金*（C-1）
        BigDecimal lastRepayPrincipal = a.subtract(
            monthRepayPrincipal.multiply(new BigDecimal(repaymentInfoParam.getTerm() - 1)));

        //首月利息=每月利息=四舍五入到2位小数（A*D/C）
        BigDecimal firstRepayInterest, monthRepayInterest;
        firstRepayInterest = monthRepayInterest = a.multiply(d).divide(c, MathContext.DECIMAL128)
            .setScale(2, BigDecimal.ROUND_HALF_UP);

        //末月利息=A*D-每月利息*（C-1）
        BigDecimal lastRepayInterest = a.multiply(d).subtract(
            firstRepayInterest.multiply(new BigDecimal(repaymentInfoParam.getTerm() - 1)))
            .setScale(2, BigDecimal.ROUND_HALF_UP);

        RepaymentInfo repaymentInfo = new RepaymentInfo();
        repaymentInfo.setMonthRepayInterest(monthRepayInterest);
        repaymentInfo.setMonthRepayPrincipal(monthRepayPrincipal);
        repaymentInfo.setFirstRepayInterest(firstRepayInterest);
        repaymentInfo.setFirstRepayPrincipal(firstRepayPrincipal);
        repaymentInfo.setLastRepayInterest(lastRepayInterest);
        repaymentInfo.setLastRepayPrincipal(lastRepayPrincipal);
        if (null != repaymentInfoParam.getLendDate() && null != repaymentInfoParam
            .getStatementDay()) {
            repaymentInfo.setFirstStatementDate(RepaymentPlanUtil
                .getFirstStatementDate(repaymentInfoParam.getLendDate(),
                    repaymentInfoParam.getStatementDay()));
        }
        return repaymentInfo;
    }

    @Override
    public Integer getFinancingAmount(BigDecimal installmentAmount, BigDecimal rate,
        BigDecimal bankRate) {
        //分期金额*（1+（执行费率—银行基础费率））注意百分比，农业银行的业务，保留到百位，如个位和十位在30及以下的，舍去，30以上的进1（如56789.99，56730.01进为56800，56730，56729.99进为56700）
        rate = rate.divide(new BigDecimal(100), MathContext.DECIMAL128);
        bankRate = bankRate.divide(new BigDecimal(100), MathContext.DECIMAL128);
        BigDecimal add = BigDecimal.ONE.add(rate.subtract(bankRate, MathContext.DECIMAL128));
        BigDecimal multiply = installmentAmount.multiply(add, MathContext.DECIMAL128)
            .setScale(2, BigDecimal.ROUND_HALF_UP);
        int i1 = multiply.setScale(0, BigDecimal.ROUND_FLOOR).intValue();
        int i = multiply.setScale(-2, BigDecimal.ROUND_FLOOR).intValue();
        if (i1 - i >= 30) {
            i = i + 100;
        }
        return i;
    }

    @Override
    public Integer getMiniBillingAmount(Integer financingAmount, BigDecimal installmentAmount,
        Integer carType) {
        if (carType == 1) {
            BigDecimal divide = new BigDecimal(financingAmount)
                .divide(new BigDecimal(0.8), MathContext.DECIMAL128);
            return divide
                .setScale(6, BigDecimal.ROUND_HALF_UP)
                .setScale(-2, BigDecimal.ROUND_CEILING ).intValue();
        } else if (carType == 2) {
            BigDecimal divide = new BigDecimal(financingAmount)
                .divide(new BigDecimal(0.7), MathContext.DECIMAL128);
            return divide
                .setScale(6, BigDecimal.ROUND_HALF_UP)
                .setScale(-2, BigDecimal.ROUND_CEILING ).intValue();
        } else {
            throw new UnsupportedOperationException("未实现");
        }
    }

    public static void main(String[] args) {
        AbcRepaymentFormula abcRepaymentFormula = new AbcRepaymentFormula();

        Integer miniBillingAmount = abcRepaymentFormula.getMiniBillingAmount(84500, null, 2);
        System.out.println(miniBillingAmount);

        RepaymentInfoParam repaymentInfoParam = new RepaymentInfoParam();
        repaymentInfoParam.setLendDate("2020-02-10");
        repaymentInfoParam.setStatementDay(28);
        repaymentInfoParam.setFinancingAmount(new BigDecimal(236900));
        repaymentInfoParam.setInstallmentAmount(new BigDecimal(148000));
        repaymentInfoParam.setRate(new BigDecimal(0.082));
        repaymentInfoParam.setTerm(36);
        repaymentInfoParam.setGracePeriod(25);
        RepaymentInfo repaymentInfo = abcRepaymentFormula.getRepaymentInfo(repaymentInfoParam);
        System.out.println(JSON.toJSONString(repaymentInfo));

        System.out.println(
            "农行：分期金额=" + repaymentInfoParam.getInstallmentAmount() + " ；融资金额=" + repaymentInfoParam
                .getFinancingAmount() + "；费率=0.082；期数="
                + repaymentInfoParam.getTerm() + "；结果：首月利息=" + repaymentInfo.getFirstRepayInterest()
                + ",首月本金=" + repaymentInfo.getFirstRepayPrincipal() + ", 每月利息=" + repaymentInfo
                .getMonthRepayInterest()
                + ",每月本金=" + repaymentInfo.getMonthRepayPrincipal() + "末月利息=" + repaymentInfo
                .getLastRepayInterest()
                + ",末月本金=" + repaymentInfo.getLastRepayPrincipal());

        RepaymentPlanParam repaymentPlanParam = new RepaymentPlanParam();
        repaymentPlanParam.setMonthRepayInterest(repaymentInfo.getMonthRepayInterest());
        repaymentPlanParam.setFinancingAmount(repaymentInfoParam.getFinancingAmount());
        repaymentPlanParam.setMonthRepayPrincipal(repaymentInfo.getMonthRepayPrincipal());
        repaymentPlanParam.setFirstRepayInterest(repaymentInfo.getFirstRepayInterest());
        repaymentPlanParam.setFirstRepayPrincipal(repaymentInfo.getFirstRepayPrincipal());
        repaymentPlanParam.setLastRepayInterest(repaymentInfo.getLastRepayInterest());
        repaymentPlanParam.setLastRepayPrincipal(repaymentInfo.getLastRepayPrincipal());

        repaymentPlanParam.setFirstStatementDate(repaymentInfo.getFirstStatementDate());
        repaymentPlanParam.setGracePeriod(28);
        repaymentPlanParam.setTerm(36);

        LocalDate now = LocalDate.parse("2023-03-29");
        LocalDate lastRepaymentDate = LocalDate.parse(RepaymentPlanUtil
            .getLastRepaymentDate(repaymentPlanParam.getGracePeriod(), repaymentPlanParam.getTerm(),
                repaymentPlanParam.getFirstStatementDate()));

        RepaymentPlan currentRepaymentPlan = RepaymentPlanUtil
            .getCurrentRepaymentPlan(now, repaymentPlanParam, lastRepaymentDate);
        System.out.println(currentRepaymentPlan);

//        List<RepaymentPlan> repaymentPlans = abcRepaymentFormula
//            .getRepaymentPlans(repaymentPlanParam);
//        System.out.println(JSON.toJSONString(repaymentPlans));

    }
}
